const mta = require('/mta_sdk/mta_analysis.js');
const http = require('/utils/util.js');
App({
  onLaunch: function (opt) {

    wx.checkSession({
      success: res => {
        console.log("有效")
      },
      fail: res => {
        //Session失效了就清除缓存
        console.log("失效")
        wx.clearStorage();
      }
    });
    this.globalData.member_id = wx.getStorageSync("member_id") || '';
    this.globalData.openid = wx.getStorageSync("openid") || '';
    this.globalData.session_id = wx.getStorageSync("session_id") || '';
    this.globalData.userInfo = wx.getStorageSync("userInfo") || '';
    // this.setToken();
    mta.App.init({
      "appID": "500615979",
      "eventID": "500615980",
      "statPullDownFresh": true,
      "statShareApp": true,
      "statReachBottom": true
    });
    
    //this.getShareTile();
  },
  onReady() {

  },
  onShow(opt) {

  },
  globalData: {
    userInfo: null,//用户信息
    hosts: "https://api.beikg.cn/Spoof/",
    appid: 'wxcd63916101feefd2',
    secret: '9cd8481fabe468858cb55b3e5e7485ab',
    template_id: '4dCPQIcg6FkIhHFMPs1XUOkKb2tQyFxP5xrxuaa0N_I',
    str: '/',
    member_id: '',
    openid: '',
    session_id: '',
    shareMess: {
      title: '',
      desc: '',
      imgUrl: '',
      path: ''
    },
    adData: ''
  },

  //获取用户数据
  getUserData: function (info, callback) {
    if (!info) {
      wx.showModal({
        title: '提示',
        content: '获取用户信息失败！',
      });
      return false;
    }

    var ssid = wx.getStorageSync("session_id");

    if (ssid && ssid != 'undefined' && ssid != '') {

      return false;
    }

    wx.login({
      success: a => {
        this.wxLogin(a.code, info, callback);
      },
      fail: b => { },

    });
  },
  //获取openid
  wxLogin: function (code, info, callback) {
    console.log("获取了code:", info)
    http.ajax("nossid", 'Login' + this.globalData.str + 'wxlogin', {
      code: code,
      appid: this.globalData.appid,
      secret: this.globalData.secret,
      avatarUrl: info.avatarUrl,
      city: info.city,
      country: info.country,
      gender: info.gender,
      language: info.language,
      nickName: info.nickName,
      province: info.province,
    }, res => {
      console.log("请求成功")
      var r = res.data.data
      this.globalData.userInfo = info;
      this.globalData.openid = r.openid;
      this.globalData.session_id = r.session_id;
      this.globalData.member_id = r.member_id;
      wx.setStorageSync('userInfo', info);
      wx.setStorageSync('openid', r.openid);
      wx.setStorageSync('session_id', r.session_id);
      wx.setStorageSync('member_id', r.member_id);
      callback(r);
    })
  },

  getShareTile: function () {
    var me = this;
    wx.request({
      url: me.globalData.hosts + 'index' + me.globalData.str + 'sharetmp',
      data: { appid: me.globalData.appid },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'PHPSESSID=' + me.globalData.session_id
      },
      success: res => {
        var data = res.data.data;
        me.globalData.shareMess.title = data.title || '';
        me.globalData.shareMess.desc = data.desc || '';
        me.globalData.shareMess.imgUrl = data.imgsrc || '';
        me.globalData.shareMess.path = data.path || ''
      }
    })
  },
  getChance: function (shareType, callback) {
    var me = this;
    return {
      title: me.globalData.shareMess.title || '@我，快来猜歌，闯关成功还送娃娃！',
      desc: me.globalData.shareMess.desc || '@我，快来猜歌，闯关成功还送娃娃！',
      path: me.globalData.shareMess.path || '/pages/index/index',
      imageUrl: me.globalData.shareMess.imgUrl || '/images/kaishi.png',
      success: ((res) => {
        if (this.globalData.member_id == '') {
          wx.showToast({
            title: '分享成功！',
            duration: 1500,
            icon: 'none',
          });
          return false;
        }
        if (res.shareTickets) {
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success: ((res) => {
              this.postShare(res.encryptedData, res.iv, callback, shareType)
            })

          });

        }
        else {

          this.postShare('', '', callback, 3)

        }
      })
    }
  },
  postShare(encryptedData, iv, callback, shareType) {
    var me = this;
    http.ajax(0, "Index" + me.globalData.str + "sharerecord", {
      member_id: wx.getStorageSync('member_id'),
      encryptedData: encryptedData,
      iv: iv,
      shareType: shareType,

    }, ((res) => {
      var r = res.data.data;
      var msg = ""
      if (r.repetition == "no") {
        //this.globalData.opportunity = r.opportunity;
        wx.setStorageSync('opportunity', r.opportunity);
        msg = '+1';
        callback();
      }
      if (r.repetition == "repetition") {
        msg = '';
        callback();
      }
      wx.showToast({
        title: res.data.msg + msg,
        duration: 1500,
        icon: 'none',
        image: '/images/icon_success.png'
      });
    })
    )
  },
  getAD: function (callback) {
    var me = this;
    wx.request({
      url: me.globalData.hosts + 'index' + me.globalData.str + 'getdata_ad',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'PHPSESSID=' + me.globalData.session_id
      },
      data: { appid: me.globalData.appid },
      success: res => {
        var data = res.data.data;
        callback(data)
      }
    })
  },
  //保存图片
  savePic(canvasid) {
    wx.canvasToTempFilePath({
      
      canvasId: canvasid,
      success: function (e) {
        
        wx.saveImageToPhotosAlbum({
          
          filePath: e.tempFilePath,
          success: function () {
            console.log(e.tempFilePath);
            wx.showToast({
              icon: "success",
              title: "保存成功"
            });
            
          },
          fail: function (t) {
            wx.showToast({
              icon: "none",
              title: "保存失败,请确保是否打开了图片权限",
              duration: 2000
            });
          },
          complete: function () {

          }
        });
      }
    });
  },
  buldingImg(canID,call){
    var me=this;
    wx.canvasToTempFilePath({
      canvasId: canID,
      success: function (e) {
        console.log(e,'生成图片成功');
        wx.uploadFile({
          url: me.globalData.hosts + 'Index/uploadimg', //仅为示例，非真实的接口地址
          filePath: e.tempFilePath,
          name: 'file',
          formData: {
            'appid': me.globalData.appid,
            'member_id': me.globalData.member_id
          },
          success: function (res) {
            console.log(res.data, 'uploadFile');
            var d = JSON.parse(res.data);
            call(d)
          },
          fail: function (res) {
            wx.showToast({
              title: '生成失败',
              icon: 'none'
            })
          }

        })
      },
      fail:function(res){
        console.log(res, '生成图片失败');
        wx.showToast({
          title: '生成失败',
          icon: 'none'
        })
      }
    })
  },
  sendForm: function (eve) {
    
    var me=this;
    console.log(me.globalData.openid);
    if (me.globalData.openid == '') {

      return false
    }

    http.ajax('ssid', 0,
      'Index/send',
      {
        "touser": me.globalData.openid,
        "template_id": me.globalData.template_id,
        "page": "/pages/index/index",
        "form_id": eve.detail.formId,
        "form_type": 1,
        "secret": me.globalData.secret,
        "appid": me.globalData.appid,
        "member_id": me.globalData.member_id,
      },
      (r) => {
        console.log("发送模板:" + JSON.stringify(r.data))
      },
    )

  },
})
